// exportUtils.js
// 数据导出工具函数

import { Utils } from './index'

/**
 * 导出工具类
 */
export class ExportUtils {
  /**
   * 处理实验数据
   * @param {Array} experimentGroups 实验组数据
   * @returns {Array} 处理后的数据
   */
  static processExperimentData(experimentGroups = []) {
    if (!experimentGroups || experimentGroups.length === 0) {
      console.warn('没有实验数据可处理')
      return []
    }

    const processedData = []
    
    experimentGroups.forEach((exp, expIdx) => {
      if (exp.periods && exp.periods.length > 0) {
        // 计算平均周期
        const avgPeriod = exp.periods.reduce((sum, p) => sum + p.duration, 0) / exp.periods.length
        
        processedData.push({
          experimentIndex: expIdx + 1,
          initialAngle: exp.initialAngle || 0,
          length: exp.length || 100,
          period: avgPeriod,
          sqrtLength: Math.sqrt((exp.length || 100) / 100),
          gravity: exp.gravity || this.calculateGravity(exp.length || 100, avgPeriod),
          periodCount: exp.periods.length,
          periods: exp.periods
        })
      } else {
        // 没有周期数据的实验
        processedData.push({
          experimentIndex: expIdx + 1,
          initialAngle: exp.initialAngle || 0,
          length: exp.length || 100,
          period: 0,
          sqrtLength: Math.sqrt((exp.length || 100) / 100),
          gravity: exp.gravity || 0,
          periodCount: 0,
          periods: []
        })
      }
    })

    return processedData
  }

  /**
   * 计算重力加速度
   * @param {number} length 摆长(cm)
   * @param {number} period 周期(s)
   * @returns {number} 重力加速度(m/s²)
   */
  static calculateGravity(length, period) {
    if (!length || !period || period === 0) return 0
    return 4 * Math.PI * Math.PI * (length / 100) / (period * period)
  }

  /**
   * 导出CSV数据
   * @param {Array} experimentGroups 实验组数据
   * @param {string} filename 文件名
   */
  static exportToCSV(experimentGroups = [], filename = '实验数据.csv') {
    if (!experimentGroups || experimentGroups.length === 0) {
      Utils.showToast('没有可导出的实验数据！', 'warning')
      return
    }

    let csv = '实验编号,初始角度(°),摆长(cm),周期编号,本周期时长(s),累计时长(s),重力加速度(m/s²)\n'
    
    experimentGroups.forEach((exp, expIdx) => {
      if (exp.periods && exp.periods.length > 0) {
        exp.periods.forEach((p, i) => {
          csv += [
            expIdx + 1,
            exp.initialAngle || 0,
            exp.length || 100,
            p.index || (i + 1),
            Utils.formatNumber(p.duration, 4),
            Utils.formatNumber(p.total || p.duration, 4),
            (i === 0 ? Utils.formatNumber(exp.gravity || 0, 4) : '')
          ].join(',') + '\n'
        })
      } else {
        csv += [
          expIdx + 1,
          exp.initialAngle || 0,
          exp.length || 100,
          '', '', '', 
          Utils.formatNumber(exp.gravity || 0, 4)
        ].join(',') + '\n'
      }
    })

    // 添加UTF-8 BOM头
    const BOM = '\uFEFF'
    const content = BOM + csv
    
    Utils.downloadFile(content, filename, 'text/csv')
    Utils.showToast('CSV数据导出成功', 'success')
  }

  /**
   * 导出JSON数据
   * @param {Array} experimentGroups 实验组数据
   * @param {string} filename 文件名
   */
  static exportToJSON(experimentGroups = [], filename = '实验数据.json') {
    if (!experimentGroups || experimentGroups.length === 0) {
      Utils.showToast('没有可导出的实验数据！', 'warning')
      return
    }

    const exportData = {
      exportTime: new Date().toISOString(),
      experimentCount: experimentGroups.length,
      experiments: experimentGroups.map((exp, index) => ({
        id: index + 1,
        initialAngle: exp.initialAngle || 0,
        length: exp.length || 100,
        startTime: exp.startTime,
        gravity: exp.gravity || 0,
        periods: exp.periods || [],
        periodCount: exp.periods ? exp.periods.length : 0,
        averagePeriod: exp.periods && exp.periods.length > 0 
          ? exp.periods.reduce((sum, p) => sum + p.duration, 0) / exp.periods.length 
          : 0
      }))
    }

    const content = JSON.stringify(exportData, null, 2)
    Utils.downloadFile(content, filename, 'application/json')
    Utils.showToast('JSON数据导出成功', 'success')
  }

  /**
   * 生成实验报告HTML
   * @param {Array} experimentGroups 实验组数据
   * @param {string} filename 文件名
   */
  static generateReport(experimentGroups = [], filename = '单摆测重力加速度实验报告.html') {
    const data = this.processExperimentData(experimentGroups)
    
    if (data.length === 0) {
      Utils.showToast('没有实验数据可生成报告！', 'warning')
      return
    }

    const htmlContent = this.generateReportHTML(data)
    Utils.downloadFile(htmlContent, filename, 'text/html')
    Utils.showToast('实验报告生成成功', 'success')
  }

  /**
   * 生成报告HTML内容
   * @param {Array} data 处理后的实验数据
   * @returns {string} HTML内容
   */
  static generateReportHTML(data) {
    const currentTime = new Date().toLocaleString('zh-CN')
    const avgGravity = data.length > 0 
      ? data.reduce((sum, d) => sum + d.gravity, 0) / data.length 
      : 0

    return `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>单摆测重力加速度实验报告</title>
    <style>
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            line-height: 1.6;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            color: #333;
            background: #f9f9f9;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1, h2 {
            color: #2c3e50;
            border-bottom: 2px solid #eee;
            padding-bottom: 10px;
        }
        h1 {
            text-align: center;
            color: #e74c3c;
        }
        .meta-info {
            background: #ecf0f1;
            padding: 15px;
            border-radius: 5px;
            margin: 20px 0;
        }
        .formula {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin: 15px 0;
            text-align: center;
            font-style: italic;
            border-left: 4px solid #3498db;
        }
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        .data-table th, .data-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        .data-table th {
            background: #3498db;
            color: white;
        }
        .data-table tr:nth-child(even) {
            background: #f2f2f2;
        }
        .summary {
            background: #d5f4e6;
            padding: 15px;
            border-radius: 5px;
            margin: 20px 0;
            border-left: 4px solid #27ae60;
        }
        .footer {
            text-align: center;
            margin-top: 30px;
            color: #7f8c8d;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>单摆测重力加速度实验报告</h1>
        
        <div class="meta-info">
            <strong>报告生成时间：</strong>${currentTime}<br>
            <strong>实验次数：</strong>${data.length} 次<br>
            <strong>平均重力加速度：</strong>${Utils.formatNumber(avgGravity, 3)} m/s²
        </div>

        <h2>实验原理</h2>
        <p>单摆在小角度摆动时，其周期公式为：</p>
        <div class="formula">
            T = 2π√(L/g)
        </div>
        <p>其中：T为周期(s)，L为摆长(m)，g为重力加速度(m/s²)</p>
        <p>由此可得重力加速度的计算公式：</p>
        <div class="formula">
            g = 4π²L/T²
        </div>

        <h2>实验数据</h2>
        <table class="data-table">
            <thead>
                <tr>
                    <th>实验编号</th>
                    <th>初始角度(°)</th>
                    <th>摆长(cm)</th>
                    <th>周期(s)</th>
                    <th>重力加速度(m/s²)</th>
                    <th>周期数</th>
                </tr>
            </thead>
            <tbody>
                ${data.map(d => `
                <tr>
                    <td>${d.experimentIndex}</td>
                    <td>${Utils.formatNumber(d.initialAngle, 1)}</td>
                    <td>${Utils.formatNumber(d.length, 1)}</td>
                    <td>${Utils.formatNumber(d.period, 3)}</td>
                    <td>${Utils.formatNumber(d.gravity, 3)}</td>
                    <td>${d.periodCount}</td>
                </tr>
                `).join('')}
            </tbody>
        </table>

        <h2>数据分析</h2>
        <div class="summary">
            <h3>统计结果</h3>
            <p><strong>实验次数：</strong>${data.length} 次</p>
            <p><strong>平均重力加速度：</strong>${Utils.formatNumber(avgGravity, 3)} m/s²</p>
            <p><strong>标准重力加速度：</strong>9.800 m/s²</p>
            <p><strong>相对误差：</strong>${Utils.formatNumber(Math.abs(avgGravity - 9.8) / 9.8 * 100, 2)}%</p>
        </div>

        <h2>实验结论</h2>
        <p>通过单摆实验测得的重力加速度为 ${Utils.formatNumber(avgGravity, 3)} m/s²，
        与标准值 9.800 m/s² 相比，相对误差为 ${Utils.formatNumber(Math.abs(avgGravity - 9.8) / 9.8 * 100, 2)}%。
        实验结果${Math.abs(avgGravity - 9.8) / 9.8 * 100 < 5 ? '较为准确' : '存在一定误差'}。</p>

        <h2>误差分析</h2>
        <ul>
            <li>测量误差：摆长测量、时间测量的精度限制</li>
            <li>系统误差：空气阻力、摆线质量、摆球不是质点等因素</li>
            <li>随机误差：人为操作、环境干扰等因素</li>
        </ul>

        <div class="footer">
            <p>本报告由精密单摆重力加速度测量实验平台自动生成</p>
        </div>
    </div>
</body>
</html>`
  }
}

export default ExportUtils
